﻿using FinScreen;
using FinScreen.Model;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace FinQuant
{
    class Program
    {
        QuantBase _quantBase = new QuantBase();
        MasterBase _masterBase = new MasterBase();
        ConcurrentQueue<string> _nots = new ConcurrentQueue<string>();

        static void Main(string[] args)
        {
            Program p = new Program();

            Console.WriteLine("Downloading Quotes...");
            p.DownloadQuotes();

            Console.ReadLine();
        }

        private void DownloadQuotes()
        {
            //ServicePointManager.DefaultConnectionLimit = 1000;

            string path = Path.Combine(@"D:\", "FinData");
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            path = Path.Combine(@"D:\FinData", "Quotes");
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            _masterBase
                .Subscribe((instrument) =>
            {
                //Task.Run(() =>
                {
                    string file = Path.Combine(@"D:\FinData", "Quotes",
                        instrument.Code.ToString() + ".csv");

                    try
                    {
                        if (!File.Exists(file))
                        {
                            FileInfo fi = new FileInfo(file);

                            if (fi.LastWriteTime.Date < DateTime.Today
                                || fi.Length < 10 * 1024)
                            {
                                Console.WriteLine("Download <" + instrument.Code.ToString() + ">");

                                WebClient c = new WebClient();
                                c.DownloadFile("http://ichart.yahoo.com/table.csv?s=" + instrument.Code.ToString(), file);

                                Console.WriteLine("****Downloaded <" + instrument.Code.ToString() + ">****");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error Download:" + instrument.Code.ToString() + ". " + ex.Message);
                        _nots.Enqueue(instrument.Code.ToString());
                    }
                }
                //);
            },
            () =>
            {
                Console.WriteLine("Download completed.");

                if (_nots.Count > 0)
                {
                    Console.WriteLine("Missing...");
                    Console.WriteLine(string.Join(",", _nots.ToArray()));
                }
            });

            Task.Run(() => { _masterBase.Load(); });
        }
    }
}
